package com.yyj1205.jsongenrator.service.Implement;

import com.alibaba.fastjson.JSONObject;
import com.yyj1205.jsongenrator.service.ParseService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @Title: ParseServiceImpl
 * @Author yyj1205
 * @Package com.yyj1205.jsongenrator.service.Implement
 * @Date 2025-01-19 16:43
 * @description:
 */
@Service
public class ParseServiceImpl implements ParseService {


    @Override
    public List<JSONObject> extractJsons(String content) {
        String regex = "```json(.|\\n)*?```";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(content);
        ArrayList<JSONObject> jsons = new ArrayList<>();
        while (matcher.find()) {
            String group = matcher.group();
            group = group.substring(7, group.length() - 3);
            group = group.replaceAll("//\\s(.*?(\\.|。)\\s)*", "");
            try{
                JSONObject json = JSONObject.parseObject(group);
                jsons.add(json);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return jsons;
    }

    @Override
    public String generateModelJson(JSONObject jsonObject) {
        return jsonObject.toJSONString();
    }

    @Override
    public String generateTableJson(JSONObject jsonObject) {
        String tableName = null;
        try {
            tableName = jsonObject.getString("name");
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return "{\n" +
                "  \"name\":\" " + tableName + "\",\n" +
                "  \"action\": {\n" +
                " \"bind\": { \"model\": \""+ tableName +"\", \"option\": {} }\n" +
                "  }\n" +
                "}";
    }

    @Override
    public String generateFormJson(JSONObject jsonObject) {
        String formName = null;
        try {
            formName = jsonObject.getString("name");
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return "{\n" +
                "  \"name\": \" " + formName + "\",\n" +
                "  \"action\": {\n" +
                " \"bind\": { \"model\": \""+ formName +"\", \"option\": {} }\n" +
                "  }\n" +
                "}";
    }
}
